package org.grottarossa.ui.core.components.tables;


import java.util.Date;
import java.util.GregorianCalendar;

import org.grottarossa.ui.DateHelper;
import org.grottarossa.ui.core.StylesConstants;
import org.grottarossa.ui.core.container.ContainerException;
import org.grottarossa.ui.core.container.TableContainer;

import com.vaadin.data.Container;
import com.vaadin.data.Property;
import com.vaadin.event.ItemClickEvent.ItemClickListener;
import com.vaadin.ui.Table;

public class TMSTable extends Table
{
	private static final long serialVersionUID = 1L;
	private static int MAX_PAGE_SIZE=40;

	/**
	 * Costruttore vuoto.
	 * */
	public TMSTable()
	{
		addStyleName(StylesConstants.TMSTABLE);
	}

	public TMSTable(org.grottarossa.template.data.pojo.table.Table data)
	{
		TableContainer tc = createContainer(data);
		setContainerDataSource(tc);
		initTable(data);
		addStyleName(StylesConstants.TMSTABLE);
	}

	@Override
	protected String formatPropertyValue(Object rowId, Object colId, Property property)
	{
		Object v = property.getValue();

		if (v instanceof GregorianCalendar )
        {
		    GregorianCalendar calendar = (GregorianCalendar) v;
            return DateHelper.DateToString(calendar.getTime());
        }
		else if(v instanceof Date)
			return DateHelper.DateToString((Date)v);

        return super.formatPropertyValue(rowId, colId, property);
	}

	protected TableContainer createContainer(org.grottarossa.template.data.pojo.table.Table data)
	{
		TableContainer tableContainer = new TableContainer();
		tableContainer.setDataTable(data);
        return tableContainer;
	}

	protected void initTable(org.grottarossa.template.data.pojo.table.Table data)
	{
		setColumnReorderingAllowed(true);
        setColumnCollapsingAllowed(true);

        this.setSizeFull();

        if ( data.isNotEmpty() )
        {
	        setVisibleColumns(data.getVisibleColumns());
	        setColumnHeaders(data.getColumnHeaders());
        }
        else
        {
			if ( data.getRecords().size() < MAX_PAGE_SIZE )
				this.setPageLength(data.getRecords().size());
			else
				this.setPageLength(MAX_PAGE_SIZE);
        }
	}
}
